import { BooleanNumber } from '@/enums';
import { DEVICE_ATTRIBUTE, VOLUME_TYPE } from '@/enums/device.enums';

export function useDeviceSetting() {
  // 获取亮度
  const getBrightness = () => {
    return new Promise((resolve, reject) => {
      uni.getScreenBrightness({
        success: res => resolve(Math.round(res.value * 100)),
        fail: error => reject(error)
      });
    });
  };

  // 设置亮度
  const setBrightness = (value: number) => {
    return new Promise<void>((resolve, reject) => {
      wxcPlugin.setBright(value, res => {
        if (res && res.success) {
          resolve();
        }
        else {
          reject(new Error('setBrightness failed'));
        }
      });
    });
  };

  let wxcPlugin;
  // #ifdef APP-PLUS
  wxcPlugin = uni.requireNativePlugin('XWC-Util');
  // #endif

  // 设置声音
  const setVolume = (value: number, volumeType: VOLUME_TYPE) => {
    return new Promise<void>((resolve, reject) => {
      if (!wxcPlugin) {
        reject(new Error('wxcPlugin is not supported'));
      }
      const result = wxcPlugin.setVolume(volumeType, value);
      if (result.success === BooleanNumber.TRUE) {
        resolve();
      }
      else {
        reject(new Error('setVolume failed'));
      }
    });
  };

  // 获取声音
  const getVolume = (volumeType: VOLUME_TYPE) => {
    return new Promise<number>((resolve, reject) => {
      if (!wxcPlugin) {
        reject(new Error('wxcPlugin is not supported'));
      }
      const result = wxcPlugin.getVolume(volumeType);
      if (result.success === BooleanNumber.TRUE) {
        resolve(result.data);
      }
      else {
        reject(new Error('getVolume failed'));
      }
    });
  };

  //
  const attributeHandlers = {
    [DEVICE_ATTRIBUTE.VOLUME_CALL]: (value: any) => {
      setVolume(value, VOLUME_TYPE.VOLUME_TYPES_CALL);
    },
    [DEVICE_ATTRIBUTE.VOLUME_ALERT]: (value: any) => {
      setVolume(value, VOLUME_TYPE.VOLUME_TYPES_ALERT);
    },
    [DEVICE_ATTRIBUTE.VOLUME_MEDIA]: (value: any) => {
      setVolume(value, VOLUME_TYPE.VOLUME_TYPES_MEDIA);
    },
    [DEVICE_ATTRIBUTE.BRIGHTNESS]: (value: any) => {
      setBrightness(value);
    },
    [DEVICE_ATTRIBUTE.SCREEN_OFF]: () => {
      console.log('>>>>关机');
    },
    [DEVICE_ATTRIBUTE.RESTART]: () => {
      wxcPlugin.reboot(ret => {
        console.log('>>>设备重启', ret);
      });
    }
  };

  const dispatchHandler = (message: Record<string, any>) => {
    // 属性设置
    Object.entries(attributeHandlers).forEach(([key, handler]) => {
      if (Reflect.has(message, key)) {
        handler(message[key]);
      }
    });
  };

  return {
    getBrightness,
    setBrightness,
    setVolume,
    getVolume,

    dispatchHandler
  };
}
